package model;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class RepositorioAutomovel {
	
	EntityManagerFactory emf;
	EntityManager em;
	
	public RepositorioAutomovel(){
		emf = Persistence.createEntityManagerFactory("dbteste");
		em = emf.createEntityManager();
	}
	
	public void salvar(Automovel auto){
		
		em.getTransaction().begin();
		em.merge(auto); //se o Objeto já existir no BD o Hibernate tentará atualizá-lo
		em.getTransaction().commit();
		emf.close();
		
	}
	
	public Automovel buscarPorId (int id){
		
		em.getTransaction().begin();
		Automovel auto = em.find(Automovel.class, id);
		em.getTransaction().commit();
		emf.close();
		return auto;
		
	}
	
	public void remover (Automovel auto){
		
		em.getTransaction().begin();
		em.remove(auto); 
		em.getTransaction().commit();
		emf.close();
	}
	
	@SuppressWarnings("unchecked")
	public List<Automovel> listarTodos(){
		
		em.getTransaction().begin();
		Query consulta = em.createNamedQuery("SELECT a FROM Automovel a");
		List<Automovel>  auto = consulta.getResultList();
		em.getTransaction().commit();
		emf.close();
		return auto;
	}
	

}
